package com.cxl.autocode.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.freemarker.FreemarkerManager;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ConfigurationHelper {

	private static Configuration cfg = null;

	public static Configuration getConfiguration(String templateDir) throws IOException {
		if (null == cfg) {
			cfg = new Configuration();
	        File templateDirFile = new File(templateDir);
	        cfg.setDirectoryForTemplateLoading(templateDirFile);
	        cfg.setLocale(Locale.CHINA);
	        cfg.setDefaultEncoding("UTF-8");
		}
		return cfg;
	}
	
	
	public static Configuration getConfiguration(ServletContext context) throws IOException, TemplateException {
		FreemarkerManager freemarker=new FreemarkerManager();
		if (null == cfg) {
			 cfg = freemarker.getConfiguration(context);
			 //cfg = new Configuration();
			// File templateDirFile = new File(context.getRealPath("")+"\\template");
			 //cfg.setDirectoryForTemplateLoading(templateDirFile);
	        //cfg.setLocale(Locale.CHINA);
	        //cfg.setDefaultEncoding("UTF-8");
		}
		return cfg;
	}
	
//	public static void main(String[] args) {
//		
//		ServletContext servletContext = ServletActionContext.getServletContext();
//		Configuration configuration = freemarkerManager.getConfiguration(servletContext);
//		Template template = configuration.getTemplate(templateFilePath);
//		File htmlFile = new File(servletContext.getRealPath(htmlFilePath));
//		File htmlDirectory = htmlFile.getParentFile();
//		if (!htmlDirectory.exists()) {
//			htmlDirectory.mkdirs();
//		}
//		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
//		
//	}
}
